package com.bm.main;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import redis.clients.jedis.Jedis;

import com.bm.util.MailUtil;
import com.bm.util.MybatisUtil;
import com.bm.util.RedisUtil;

//持久化类
public class InMysqlMain {
	private static Logger logger=LogManager.getLogger(InMysqlMain.class);
	
	public static void main(String[] args) {
		persistencetest();
	}
	
	
	//redis数据持久化
public static  void  persistencetest(){
	Thread thread= new Thread(new Runnable() {
		@Override
		public void run() {
			while(true){
				  Jedis jedis=RedisUtil.getJedis();
				 try {
					 //获取交易信息条数
					 long len=jedis.llen("transactionsifno");
					 if(len<1000){
					     Thread.sleep(10);
						 System.out.println("等待数据..."+len);
					 }else{
						 //写库
						 insertMysql(jedis);
					 }
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					System.out.println(e.toString());
					logger.error("【insert to mysql】 Thread error:"+e.toString());
					//MailUtil.send("【insert to mysql】 Thread error:", e.toString());
				}finally{
					//System.out.println("回收jedis...");
					RedisUtil.returnResource(jedis);
				}
			}
		}
	});
	thread.start();
	}

	public static String insertMysql(Jedis jedis){
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			int converterror=0;
			 System.out.println("开始插入....");
			 String resmessage="";
			 try {
				 long aTime=System.currentTimeMillis();
				 SqlSession sqlSession=MybatisUtil.getSqlSession();
				 long btime=System.currentTimeMillis();
				 List<String> result=jedis.lrange("transactionsifno", 0, 999);
				 List<Hashtable<Object, Object>> list=new ArrayList<Hashtable<Object,Object>>();
				 //解析redis数据，存入list，mybatis执行循环写入数据,解析失败的数据另外存储
				 for (String string : result) {
					 if(true){ //解析成功
						 Hashtable<Object, Object> hashTable= new Hashtable<Object, Object>();
						 hashTable.put("key1", string);
						 hashTable.put("cretime", format.format(new Date()));
						 list.add(hashTable);
					 }else{//解析失败的数据缓存到redis其他库
						 //缓存到redis后，记录转化错误数
						 if(jedis.rpush("transactionsifno"+format.format(new Date()), string)==1)
							 converterror++;
					 }
				 }
				 long cTime=System.currentTimeMillis();
				 int i=sqlSession.insert("insertqqqq", list);
				 long dTime=System.currentTimeMillis();
			    //插入成功移除前1000条数据
			     if(i>0&&(i+converterror)==1000){
			    	 sqlSession.commit();
			    	 long eTime=System.currentTimeMillis();
					 jedis.ltrim("transactionsifno", 1000, -1);
					 long fTime=System.currentTimeMillis();
					 logger.error("【建立数据库连接耗时】"+(btime-aTime)+"【插入1000条数据耗时】"+(dTime-cTime)+"【redis剔除1000条数据耗时】"+(fTime-eTime));
					 resmessage="成功插入1000条数据";
			    }else
			    	MailUtil.send("无法正常写库，请立即处理!!", "数据解析错误，没有正确处理，请立即处理，否则程序阻塞导致数据无法正常写库!!");
			     
			} catch (Exception e) {
				resmessage=e.toString();
				logger.error("【insert to mysql】 insert fail:"+e.toString());
				//异常邮件提醒
				//MailUtil.send("【insert to mysql】 insert fail:", e.toString());
			}
			 
			return resmessage;
	}
}
